package com.ruoyi.lxy.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StreamUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.lxy.domain.bo.TProjectBo;
import com.ruoyi.lxy.domain.vo.TProjectVo;
import com.ruoyi.lxy.service.ITProjectService;
import com.ruoyi.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.lxy.domain.vo.TTravelagenVo;
import com.ruoyi.lxy.domain.bo.TTravelagenBo;
import com.ruoyi.lxy.service.ITTravelagenService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 旅行社
 *
 * @author ruoyi
 * @date 2023-08-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/lxy/travelagen")
public class TTravelagenController extends BaseController {

    private final ITTravelagenService iTTravelagenService;
    private final ITProjectService iTProjectService;
    private final ISysUserService userService;

    /**
     * 查询旅行社列表
     */
    @SaCheckPermission("lxy:travelagen:list")
    @GetMapping("/list")
    public TableDataInfo<TTravelagenVo> list(TTravelagenBo bo, PageQuery pageQuery) {
        System.out.println(bo.getProjectIds());
        return iTTravelagenService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出旅行社列表
     */
    @SaCheckPermission("lxy:travelagen:export")
    @Log(title = "旅行社", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TTravelagenBo bo, HttpServletResponse response) {
        List<TTravelagenVo> list = iTTravelagenService.queryList(bo);
        ExcelUtil.exportExcel(list, "旅行社", TTravelagenVo.class, response);
    }

    /**
     * 获取旅行社详细信息
     * @param id 主键
     */
    @SaCheckPermission("lxy:travelagen:query")
    @GetMapping(value = { "/{id}"})
    public R<Map<String,Object>> getInfo(@PathVariable(value = "id", required = false) Long id) {
        Map<String,Object> ajax=new HashMap<>();
        if(ObjectUtil.isNotNull(id)){
            ajax.put("agency",iTTravelagenService.queryById(id));
            ajax.put("projectIds",iTProjectService.selectProjectListByAgencyId(id));
        }
        return R.ok(ajax);
    }

    /**
     * 新增旅行社
     */
    @SaCheckPermission("lxy:travelagen:add")
    @Log(title = "旅行社", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TTravelagenBo bo) {
        // 是否可操作
        SysUser user=iTTravelagenService.transfer(bo);
        //检查账号是否已经存在
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        // 新增到sys_user，同时设置旅行社
        if(userService.insertUser(user)<=0){
            return R.fail();
        }
        bo.setId(user.getUserId());
        return toAjax(iTTravelagenService.insertByBo(bo));
    }

    /**
     * 修改旅行社
     */
    @SaCheckPermission("lxy:travelagen:edit")
    @Log(title = "旅行社", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TTravelagenBo bo) {
        // 是否可操作
//        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
        SysUser user=iTTravelagenService.transfer(bo);
        //检查账号是否已经存在
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        // 新增到sys_user，同时设置旅行社
        if(userService.updateUser(user)<=0){
            return R.fail();
        }
        return toAjax(iTTravelagenService.updateByBo(bo));
    }

    /**
     * 修改旅行社的状态
     */
    @SaCheckPermission("lxy:travelagen:edit")
    @Log(title = "旅行社", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody TTravelagenBo bo) {
        //是否有权限删除
        // userService.checkUserAllowed(user);
        //校验用户是否有数据权限
        // userService.checkUserDataScope(user.getUserId());
        SysUser user=iTTravelagenService.transfer(bo);
        if(userService.updateUserStatus(user)<=0){
            return R.fail();
        }
        return toAjax(iTTravelagenService.updateUserStatus(bo));
    }

    /**
     * 重置密码
     */
    @SaCheckPermission("lxy:travelagen:resetPwd")
    @Log(title = "旅行社管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody TTravelagenBo bo) {
        //是否有权限删除
        SysUser user=iTTravelagenService.transfer(bo);
        if(userService.resetPwd(user)<=0){
            return R.fail();
        }
        return toAjax(iTTravelagenService.resetPwd(bo));
    }

    /**
     * 根据旅行社编号获取项目
     */
    @SaCheckPermission("lxy:travelagen:query")
    @GetMapping("/authProject/{id}")
    public R<Map<String, Object>> authProject(@PathVariable Long id) {
        TTravelagenVo tTravelagenVo=iTTravelagenService.queryById(id);
        List<TProjectVo> projects=iTProjectService.selectProjectsByAgencyId(id);
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("agency",tTravelagenVo );
        ajax.put("projects",  projects );
        return R.ok(ajax);
    }

    /**
     * 旅行社与项目关联
     */
    @SaCheckPermission("lxy:travelagen:edit")
    @Log(title = "旅行社管理", businessType = BusinessType.GRANT)
    @PutMapping("/authProject")
    public R<Void> insertAuthRole(Long agencyId, Long[] projectIds) {
        //是否有权限
//        userService.checkUserDataScope(userId);
        iTTravelagenService.updateAgencyProject(agencyId,projectIds);
        return R.ok();
    }
    /**
     * 删除旅行社
     *
     * @param ids 主键串
     */
    @SaCheckPermission("lxy:travelagen:remove")
    @Log(title = "旅行社管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        if(userService.deleteUserByIds(ids)<=0){
            return R.fail();
        }
        return toAjax(iTTravelagenService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
    /**
     * 停用旅行社
     */
    @SaCheckPermission("lxy:travelagen:edit")
    @Log(title = "旅行社管理", businessType = BusinessType.GRANT)
    @PutMapping("/{ids}")
    public R<Void> stopStatus(@NotEmpty(message = "主键不能为空")@PathVariable Long[] ids) {
        for(Long id : ids){
            SysUser user=new SysUser();
            user.setUserId(id);
            user.setStatus("1");
            userService.updateUserStatus(user);

            TTravelagenBo bo=new TTravelagenBo();
            bo.setId(id);
            bo.setStatus(1);
            iTTravelagenService.updateUserStatus(bo);
        }
        return R.ok();
//        return toAjax(iTTravelagenService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
